package com.study.sbsummary.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.regex.Pattern;

public final class IntegerExtension {
    public static final String COMMA = ",";

    private IntegerExtension() {
    }

    private static boolean isInt(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    public static boolean isIntArray(String elements, String separator) {
        if (StringUtils.isEmpty(elements)) {
            return false;
        } else {
            String[] stringIds = elements.split(separator);
            if (stringIds.length == 0) {
                return false;
            } else {
                for(int i = 0; i < stringIds.length; ++i) {
                    if (StringUtils.isEmpty(stringIds[i]) || !isInt(stringIds[i])) {
                        return false;
                    }
                }

                return true;
            }
        }
    }

    public static int[] toIntArray(String elements, String separator) {
        if (StringUtils.isEmpty(elements)) {
            return null;
        } else {
            String[] stringIds = elements.split(separator);
            if (stringIds.length == 0) {
                return null;
            } else {
                int[] intIds = new int[stringIds.length];

                for(int i = 0; i < stringIds.length; ++i) {
                    if (StringUtils.isEmpty(stringIds[i]) || !isInt(stringIds[i])) {
                        throw new IllegalArgumentException(stringIds[i] + "不是数字");
                    }

                    intIds[i] = Integer.parseInt(stringIds[i]);
                }

                return intIds;
            }
        }
    }

    public static int getValue(Integer integerValue, int defaultValue) {
        return integerValue == null ? defaultValue : integerValue;
    }
}
